<template>
  <div class="leads-pool-container">
    <!-- 合并查询和操作区域为一行 -->
    <div class="operation-header">
      <!-- 左侧查询区域 -->
      <div class="search-bar">
        <el-input
            v-model="searchForm.investorName"
            placeholder="请输入投资方名称"
            clearable
            style="width: 200px; margin-right: 10px"
        />
        <el-select
            v-model="searchForm.stage"
            placeholder="线索阶段"
            clearable
            style="width: 160px; margin-right: 10px"
        >
          <el-option
              v-for="item in stageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="info" @click="goToIntelligentClue">智慧线索</el-button>
      </div>

      <!-- 右侧操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="openDialog('create')">新增</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
      </div>
    </div>

    <!-- 线索表格 -->
    <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px"
        :header-cell-style="{ background: '#f5f7fa' }"
        v-loading="loading"
    >
      <el-table-column
          type="selection"
          width="55"
      />
      <el-table-column
          prop="investor"
          label="投资方"
      />
      <el-table-column
          prop="enterpriseType"
          label="企业类型"
      />
      <el-table-column
          prop="region"
          label="行政区划"
      />
      <el-table-column
          prop="projectOverview"
          label="项目概况"
          show-overflow-tooltip
      />
      <el-table-column
          prop="industryCategory"
          label="项目产业类别"
      />
      <el-table-column
          prop="stage"
          label="线索阶段"
      />
      <el-table-column
          prop="status"
          label="线索状态"
      />
      <el-table-column
          prop="source"
          label="线索来源"
      />
      <el-table-column
          prop="follower"
          label="跟进人"
      />
      <el-table-column
          prop="daysLeft"
          label="未跟进天数"
      />
      <el-table-column
          prop="remark"
          label="备注"
          show-overflow-tooltip
      />
      <el-table-column
          label="操作"
          width="180"
          align="center"
      >
        <template #default="scope">
          <div class="operation-buttons">
            <el-button
                type="warning"
                icon="el-icon-edit"
                @click="openDialog('edit', scope.row)"
                size="small"
            >编辑</el-button>
            <el-button
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                size="small"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 10px; text-align: right"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <el-form-item label="投资方" prop="investor">
          <el-input v-model="formData.investor" placeholder="请输入投资方名称" />
        </el-form-item>
        <el-form-item label="企业类型" prop="enterpriseType">
          <el-input v-model="formData.enterpriseType" placeholder="请输入企业类型" />
        </el-form-item>
        <el-form-item label="行政区划" prop="region">
          <el-input v-model="formData.region" placeholder="请输入行政区划" />
        </el-form-item>
        <el-form-item label="项目概况" prop="projectOverview">
          <el-input
              v-model="formData.projectOverview"
              type="textarea"
              placeholder="请输入项目概况"
          />
        </el-form-item>
        <el-form-item label="项目产业类别" prop="industryCategory">
          <el-input v-model="formData.industryCategory" placeholder="请输入产业类别" />
        </el-form-item>
        <el-form-item label="线索阶段" prop="stage">
          <el-select v-model="formData.stage" placeholder="请选择线索阶段">
            <el-option
                v-for="item in stageOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="线索状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择线索状态">
            <el-option label="有效线索" value="有效线索" />
            <el-option label="无效线索" value="无效线索" />
          </el-select>
        </el-form-item>
        <el-form-item label="线索来源" prop="source">
          <el-input v-model="formData.source" placeholder="请输入线索来源" />
        </el-form-item>
        <el-form-item label="跟进人" prop="follower">
          <el-input v-model="formData.follower" placeholder="请输入跟进人" />
        </el-form-item>
        <el-form-item label="未跟进天数" prop="daysLeft">
          <el-input v-model.number="formData.daysLeft" placeholder="请输入未跟进天数" type="number" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="handleSave"
          >确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const api = axios.create({
  // 环境变量的基础地址 + 固定的 /api 路径
  baseURL: `${import.meta.env.VITE_API_BASE_URL}`,
  timeout: 10000
});



const stageOptions = [
  { label: '意向登记', value: '意向登记' },
  { label: '初步判断', value: '初步判断' }
]

// 查询表单
const searchForm = reactive({
  investorName: '',
  stage: '',
})

// 表格数据
const tableData = ref([])
// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const formData = reactive({
  id: '',
  investor: '',
  enterpriseType: '',
  region: '',
  projectOverview: '',
  industryCategory: '',
  stage: '',
  status: '',
  source: '',
  follower: '',
  daysLeft: null,
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  investor: [{ required: true, message: '请输入投资方名称', trigger: 'blur' }],
  stage: [{ required: true, message: '请选择线索阶段', trigger: 'change' }],
  status: [{ required: true, message: '请选择线索状态', trigger: 'change' }]
})

// 获取线索列表
const getLeadsList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await api.get('/api/clue_management', { params })
    if (response.data.success) {
      // 转换字段名
      tableData.value = response.data.data.list.map(item => ({
        id: item.id,
        investor: item.investor,
        enterpriseType: item.enterpriseType,
        region: item.region,
        projectOverview: item.projectOverview,
        industryCategory: item.industryCategory,
        stage: item.stage,
        status: item.status,
        source: item.source,
        follower: item.follower,
        daysLeft: item.daysLeft,
        remark: item.remark
      }))
      pagination.total = response.data.data.total
    }
  } catch (error) {
    console.error('获取线索列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}


// 查询
const handleSearch = () => {
  pagination.currentPage = 1
  getLeadsList()
}

// 重置查询条件
const handleReset = () => {
  searchForm.investorName = ''
  searchForm.stage = ''
  handleSearch()
}

// 每页条数改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getLeadsList()
}

// 当前页码改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getLeadsList()
}

// 打开弹窗（新增/编辑）
const openDialog = (type, row = {}) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增线索' : '编辑线索'

  // 重置表单到初始状态
  resetForm()

  if (type === 'edit') {
    // 编辑时回显数据
    nextTick(() => {
      for (const key in formData) {
        formData[key] = row[key] || ''
      }
    })
  }
}

// 新增重置表单的方法
const resetForm = () => {
  // 清空表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  formData.daysLeft = null

  // 清除表单验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const goToIntelligentClue = () => {
  router.push('/deepseek')
}

// 保存（新增/编辑）
const handleSave = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (formData.id) {
          response = await api.put(`/api/clue_management/${formData.id}`, formData)  // 使用 api
        } else {
          response = await api.post('/api/clue_management', formData)  // 使用 api
        }

        if (response.data.success) {
          ElMessage.success(formData.id ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          getLeadsList()
        } else {
          ElMessage.error('操作失败: ' + response.data.message)
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '此操作将永久删除该线索, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const response = await api.delete(`/api/clue_management/${row.id}`)
      if (response.data.success) {
        ElMessage.success('删除成功')
        getLeadsList()
      } else {
        ElMessage.error('删除失败: ' + response.data.message)
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出
const handleExport = async () => {
  try {
    const params = {
      ...searchForm
    }

    const response = await api.get(' /api/clue_management/export', {  // 使用 api
      params,
      responseType: 'blob'
    })

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '线索列表.xlsx')
    document.body.appendChild(link)
    link.click()
    link.remove()

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}
// 在组件挂载时自动获取数据
onMounted(() => {
  getLeadsList()
})
</script>

<style scoped>
.leads-pool-container {
  padding: 20px;
}
.operation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
/* 左侧查询区域 */
.search-bar {
  display: flex;
  align-items: center;
}

/* 右侧操作按钮 */
.action-buttons {
  display: flex;
  gap: 10px;
}
.table-operation {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: right;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>